#coding=utf-8
'''
Created on 2015年4月16日

@author: leoZ
'''
from ftplib import FTP
import logging
import os
logging.basicConfig()
log = logging.getLogger("FtpReceive")
log.setLevel(logging.DEBUG)
def printDir(line):
    print line.decode('gbk')

class RetrbinaryHandler(object):
    fileSize = 0
    fileCurSize = 0
    fileHandler = None
    showCnt =0
    def showTransferInfo(self):
        #不用每次都显示，太多了。每80次，打印一次就可以了。
        self.showCnt += 1
        if (self.showCnt % 80) == 0 or (self.fileCurSize == self.fileSize):
            log.debug("文件总大小:%s, 已下载文件大小:%s" %(self.fileSize, self.fileCurSize),)
     
    def handler(self, data):
        self.fileCurSize += len(data)
        self.fileHandler.write(data)
        self.showTransferInfo()
def strCodeConver(src):
    return src.decode("utf-8").encode("gbk")
    
class FtpClient(object):
    ftp = None
    options = {}
    #读取配置信息
    #初始化链接    
    def initFtpServer(self, debugLevel, host, port, user, passwd):
        self.options["debugLevel"] = debugLevel
        self.options["host"] = host
        self.options["port"] = port
        self.options["user"] = user
        self.options["passwd"] = passwd
        self.ftp = FTP()
        self.ftp.set_debuglevel(self.options["debugLevel"])
        log.debug("FTP init:" + str(self.options))
        self.ftp.set_pasv(False)
        self.ftp.connect(self.options["host"], self.options["port"])
        self.ftp.login(self.options["user"], self.options["passwd"])
        self.ftp.getwelcome()
    #获取文件大小
    def getFileSize(self, filePath, fileName):
        self.ftp.cwd(filePath)
        return self.ftp.size(fileName)
    
    def checkDstPath(self, dstPath):
        if not os.path.exists(dstPath):
            os.makedirs(dstPath.decode("utf-8"))
    #下载文件
    def downloadFile(self, fileName, srcPath, dstPath):
        log.debug("开始下载文件:%s 从源目录:%s,到目标目录:%s" %(fileName, srcPath, dstPath))
        #更改目录
        log.debug("从FTP服务器上进入目录:" + strCodeConver(srcPath))
        self.ftp.cwd(strCodeConver(srcPath))
        #检查目标目录是否存在
        self.checkDstPath(dstPath)
        #下载文件
        retrbinaryHandler = RetrbinaryHandler()
        retrbinaryHandler.fileSize = self.ftp.size(strCodeConver(fileName))
        retrbinaryHandler.fileHandler = open(dstPath+"/" + fileName,"wb") 
        log.debug("从FTP服务器上接收文件:" + strCodeConver(fileName))
        self.ftp.retrbinary("RETR " + strCodeConver(fileName),retrbinaryHandler.handler)
        retrbinaryHandler.fileHandler.close()
        log.debug("完成下载文件:%s 源文件大小:%d,下载大小:%d" %(fileName, retrbinaryHandler.fileSize, retrbinaryHandler.fileCurSize))
    
    def cleanFtpReceive(self):
        self.ftp.close()
        log.debug("关闭ftp链接")
if __name__ == '__main__':
    ftpReceive = FtpClient()
    ftpReceive.test2()